﻿using System;
using System.Windows;
using BathroomLocator.Phone.Models;
using BathroomLocator.Phone.ViewModel;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Controls.Maps.Platform;
using Microsoft.Phone.Shell;

namespace BathroomLocator.Phone.Pages
{
    public partial class BathroomLocationDetailViewPage : PhoneApplicationPage
    {
        public BathroomLocationDetailViewPage()
        {
            InitializeComponent();

            var viewModel = new BathroomLocationDetailViewPageViewModel();

            this.DataContext = viewModel;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            var viewModel = this.DataContext as BathroomLocationDetailViewPageViewModel;
            if (viewModel != null)
            {
                viewModel.BathroomLocation = PhoneApplicationService.Current.State["CurrentBathroomLocation"] as BathroomLocation;

                AddBathroomPushpin(viewModel.BathroomLocation);
            }
        }

        private void AddBathroomPushpin(BathroomLocation bathroomLocation)
        {
            double latitude;
            double longitude;
            double.TryParse(bathroomLocation.GPSLatitude, out latitude);
            double.TryParse(bathroomLocation.GPSLongitude, out longitude);

            Pushpin pushpin = new Pushpin()
            {
                Location = new Location
                {
                    Latitude = latitude,
                    Longitude = longitude
                },
                Content = bathroomLocation.FacilityName
            };
            bathroomMap.Children.Add(pushpin);
            bathroomMap.SetView(pushpin.Location, 15);
        }

        private void OnEditClick(object sender, RoutedEventArgs e)
        {
            var viewModel = this.DataContext as BathroomLocationDetailViewPageViewModel;
            if (viewModel != null)
            {
                NavigationService.Navigate(new Uri("/Pages/BathroomLocationDetailsEditPage.xaml?editData=true", UriKind.Relative));
            }
        }
    }
}